package com.ccrego.haiyi.account;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.ccrego.haiyi.account.login.LoginActivity;
import com.ccrego.haiyi.common.http.MyHttpRequest;
import com.ccrego.haiyi.common.http.TokenInfo;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;


/**
 * 账户的管理类
 *
 *
 * @Author: PV
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2016/7/12 16:36
 * @Version: 1.0.0
 */
public class AccountManager {
    private static final String TAG = AccountManager.class.getSimpleName();

    private Context mContext;
    private static TokenInfo mTokenInfo; // token info 是个单例， 且不能为空
    private static Account mAccount;  // 账户类可以为空， 外界访问这个对象的时候如果是空值， 则说明当前账户没有登录或者登录过期了
    private static AccountManager mAccountManager;

    AccountManager(Context context) {
        mContext = context;
    }

    public static AccountManager getInstance(Context context) {
        if (mAccountManager == null) {
            mAccountManager = new AccountManager(context);
        } else {
            mAccountManager.mContext = context;
        }
        return mAccountManager;
    }

    /**
     * 获取当前用户对象
     *
     * 对外部提供的接口，获取当前的账户类
     *
     * 如果当前账户过期，或者没有登录，则返回null
     *
     * @return
     */
    public static Account getCurrentAccount() {
        // 没有登录，或者登录失效
        if (!isTokenValid()) {
            Log.w(TAG, "用户还没有登或者token失效了");
            return null;
        }

        // 没有用户数据
        if (mAccount == null) {
            mAccount = Account.createFromSp();
            if (TextUtils.isEmpty(mAccount.getPassWord())) {
                return null;
            }
        }

        // 返回用户数据
        return mAccount;
    }

    public static TokenInfo getTokenInfo() {
        if (mTokenInfo == null) {
            mTokenInfo = TokenInfo.createFromSp();
        }
        return mTokenInfo;
    }


    /**
     * 判断token是否有效后
     * 无效 刷新token
     *
     * @return
     */
    public static boolean toRefreshToken(Context context) {
         Log.e("scsa","dssssd111");
        TokenInfo tokenInfo = getTokenInfo();
        if (tokenInfo.getExpiresAt() == null) {
            return false;
        }
//        try {
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.CHINESE);
//            long expiresAt = dateFormat.parse(tokenInfo.getExpiresAt()).getTime();
//            long currTime = Calendar.getInstance().getTimeInMillis();
//            if (expiresAt - currTime <= 60000) { //604800000为7天的毫秒数
                refreshToken(context);
                return true;
            }
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        return false;
//    }

    /**
     * 刷新token接口
     */
    private static void refreshToken(final Context context) {
        String url = UrlCenter.UPDATATOKEN;
        IHttpRequest request = new MyHttpRequest(context);
        request.get(url, null, new DataRequestListener<TokenInfo>(TokenInfo.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(TokenInfo token) {
                super.onSuccess(token);
                Log.e("token23",token.toString());
                updateTokenInfo(token);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
               //授权失败后重新登录
                EasyToast.showToast(context,"登录超时，请重新登录");
                AccountManager.getTokenInfo().clear();
                LoginActivity.start(context);
            }
        });
    }


    /**
     * 更新token的信息
     *
     * 用户登录之后会获取到token信息，用户需要调用此方法保存
     *
     * @param tokenInfo
     * @return
     */
    public static TokenInfo updateTokenInfo(TokenInfo  tokenInfo) {
        if (tokenInfo != null) {
            mTokenInfo = getTokenInfo();
            mTokenInfo.setAccessToken(tokenInfo.getAccessToken());
            mTokenInfo.setServerTime(tokenInfo.getServerTime());
            mTokenInfo.setRefreshToken(tokenInfo.getRefreshToken());
            mTokenInfo.setExpiresAt(tokenInfo.getExpiresAt());
            mTokenInfo.setMacKey(tokenInfo.getMacKey());
            mTokenInfo.setUser_id(tokenInfo.getUser_id());
        }
        return mTokenInfo;
    }


    /**
     * 判断token是否有效
     * @return
     */
    public static boolean isTokenValid() {
        boolean ret;
        TokenInfo tokenInfo = getTokenInfo();
        if (tokenInfo == null) {
            ret = false;
        } else {
//            if (TextUtils.isEmpty(tokenInfo.getAccessToken())) {
//                ret = false;
//          /*  } else if(){  //expires_at='2016-08-01T16:21:58.218+0800', server_time='2016-07-18T16:21:58.218+0800'
//                // TODO 判断token的有效期
//                */
//            }else
                {
                ret = true;
            }
        }

        return ret;
    }


    /**
     * 退出登录
     * clear cache
     */
    public void clear() {
        getTokenInfo().clear();
        // TODO clean more        e.g image cache/ thumbnail
    }


    /**
     * 设置当前账户信息
     * 从服务器获取用户信息后调用此方法保存用户信息
     *
     * @param account
     */
    public static void setCurrentAccount(Account account) {
        if (getCurrentAccount() != null && !TextUtils.isEmpty(getCurrentAccount().getPassWord())) {
            account.setPassWord(getCurrentAccount().getPassWord());
            Log.e("进来了",getCurrentAccount().getPassWord());
        }
        mAccount = Account.createFrom(account);
    }

}
